package br.com.me.ceap;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

/**
 * Helps to create a jar file with any kind of resources.
 * <p/>
 * This new class simplifies the way we use the {@link ByteArrayOutputStream} and {@link JarOutputStream}
 */
public class JarBundler {
// ------------------------------ FIELDS ------------------------------

    private ByteArrayOutputStream stream;
    private JarOutputStream jarFile;

// --------------------------- CONSTRUCTORS ---------------------------

    public JarBundler() {
        stream = new ByteArrayOutputStream();
        try {
            jarFile = new JarOutputStream(stream, new Manifest());
        } catch (IOException e) {
            throw new RuntimeException("Error creating jar output stream", e);
        }
    }

// ------------------------ CANONICAL METHODS ------------------------

    @Override
    public void finalize() throws Throwable {
        super.finalize();
        this.close();
    }

    public void close() throws IOException {
        jarFile.close();
    }

// -------------------------- OTHER METHODS --------------------------

    public void addEntry(final File mappingFile) {
        try {
            this.addEntry(mappingFile.getName(), IOUtils.toByteArray(new FileInputStream(mappingFile)));
        } catch (IOException e) {
            throw new RuntimeException("Error adding entry from file", e);
        }
    }

    /**
     * Adds a new entry in the jar file, using {@link JarEntry} class
     *
     * @param fileName The name of file that will be created into the jar file
     * @param bytes    The byte array that represents the file
     */
    public void addEntry(String fileName, byte[] bytes) {
        JarEntry jarEntry = new JarEntry(fileName);
        jarEntry.setTime(System.currentTimeMillis());
        jarEntry.setSize(bytes.length);
        try {
            jarFile.putNextEntry(jarEntry);
            jarFile.write(bytes, 0, bytes.length);
            jarFile.closeEntry();
        } catch (IOException e) {
            throw new RuntimeException("Exception when adding Entry", e);
        }
    }

    public byte[] toByteArray() {
        try {
            jarFile.flush();
            this.close();
            return stream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Error finalizing JarBundler's jar file in bytes", e);
        }
    }
}
